﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using System.Xml.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Net;

namespace Medianamik.Core.Logging
{
    [LayoutRenderer("mkerror")]
    public sealed class ErrorLayoutRenderer : LayoutRenderer
    {
        
        protected override int GetEstimatedBufferSize(LogEventInfo ev)
        {
            return 8000;
        }

        protected override void Append(StringBuilder builder, LogEventInfo ev)
        {
            builder.Append("<h1>" + (ev.Message ?? string.Empty) +"</h1>"); 
            Exception currentException = ev.Exception != null && ev.Exception is HttpUnhandledException 
                ? ev.Exception.InnerException 
                : ev.Exception;
            while(currentException != null)
            {
                AppendException(builder, currentException);
                builder.AppendLine("<br />");
                currentException = currentException.InnerException;
            }
            if (HttpContext.Current != null)
            {
                var request = HttpContext.Current.Request;
                AppendCollection(builder, request.QueryString , "Query String");
                builder.AppendLine("<br />");
                AppendCollection(builder, request.Cookies , "Cookies");
                builder.AppendLine("<br />");
                AppendCollection(builder, request.Form, "Form Values");
                builder.AppendLine("<br />");
                AppendCollection(builder, request.ServerVariables , "Server Variables");
            }
        }

        private void AppendException(StringBuilder pBuilder, Exception pException)
        {
            var table = new ExceptionTableBuilder(pException).Build(); 
            pBuilder.Append(table);
        }

        private void AppendCollection(StringBuilder pBuilder ,NameValueCollection pCollection , string pTitle)
        {

            var table = new NameValueCollectionTableBuilder(pCollection, pTitle).Build();
            pBuilder.Append(table);
        }

        private void AppendCollection(StringBuilder pBuilder, HttpCookieCollection pCollection, string pTitle)
        {
            var table = new HttpCookieCollectionTableBuilder(pCollection, pTitle).Build(); 
            pBuilder.Append(table);            
        }

        

        

        
    }
}
